package game.tictactoe.pojo;

import game.tictactoe.util.Utils;

import java.util.ArrayList;
import java.util.List;

public class AIPlayerImpl extends Player
{
		
	public AIPlayerImpl(Seed mySeed)
	{
		super(mySeed);
	}
	
	@Override
	public int getNextMove(Board board)
	{
		int[] result = new int[]{-1,-1};
		Best bestMove = chooseMove(mySeed, board);
		result = bestMove.getMove();
		return Utils.getMoveFromArrayIndices(result);
	}

	public Best chooseMove(Seed seed, Board board)
	{
		Best myBest = new Best();
		Best reply;
			
		if(board.isBoardFull() || hasPlayerWon(mySeed, board) || hasPlayerWon(oppSeed, board))
		{
			myBest.setMove(new int[]{});
			int score;
			if(hasPlayerWon(mySeed, board))
			{
				score = +1;
			}
			else if(hasPlayerWon(oppSeed, board))
			{
				score = -1;
			}
			else 
			{
				score = 0;
			}
			myBest.setScore(score);
			return myBest;
		}
		
		List<int[]> nextMoves = generateAllPossibleMoves(board);
		
		if(seed == mySeed)
		{
			myBest.setScore(-2);
		}
		else
		{
			myBest.setScore(2);
		}
		
		for(int[] move : nextMoves)
		{
			int rowIndex = move[0];
			int colIndex = move[1];
			board.isMoveValid(rowIndex, colIndex, seed);
			reply = chooseMove((seed == mySeed)?oppSeed:mySeed, board);
			board.undoMove(rowIndex, colIndex, seed);
			if((seed == mySeed && reply.getScore() > myBest.getScore()) 
					|| (seed == oppSeed && reply.getScore() < myBest.getScore()) )
			{
				myBest.setMove(move);
				myBest.setScore(reply.getScore());
			}
		}
		
		return myBest;
	}
		
	private List<int[]> generateAllPossibleMoves(Board board)
	{
		List<int[]> nextMoves = new ArrayList<int[]>();
		
		if(hasPlayerWon(mySeed, board) || hasPlayerWon(oppSeed, board))
		{
			return nextMoves;
		}
		
		for(int i=0; i<board.getRowIndex(); i++)
		{
			for(int j=0; j<board.getColumnIndex(); j++)
			{
				if(board.getCellValue(i, j).compareTo(Seed.EMPTY) == 0)
				{
					nextMoves.add(new int[]{i,j});
				}
			}
		}	
		return nextMoves;
	}


}
